package com.xy.bizportdemo.util;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.provider.Telephony;
import android.util.Log;

import com.xy.bizportdemo.database.SmsDBManager;
import com.xy.bizportdemo.database.entity.MessageItem;
import com.xy.bizportdemo.inserttool.XyCallback;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 导入信息的工具类
 * Created by XIAOYUAN on 2016/11/29.
 */
public class ImportDataUtil {
    private static final String TAG = "ImportDataUtil";

    public static void importData(final Context context, InputStream is) {
        final List<ContentValues> valueList = new ArrayList<ContentValues>();
        try {
            XmlPullParseUtil.parseGainDataByTagName(is, new String[] { "string" }, new XyCallback() {

                @Override
                public void execute(Object... objects) {
                    MessageItem item = new MessageItem();
                    String phone = (String) objects[1];
                    String content = (String) objects[2];
                    item.setAddress(phone);
                    item.setBody(content);
                    item.setDate(String.valueOf(System.currentTimeMillis()));
                    item.setType(MessageItem.MESSAGE_TYPE_INBOX);
                    item.setSource(MessageItem.MESSAGE_SOURCE_USER);
                    valueList.add(item.getContentValues());
                }
            });

            SmsDBManager.getInstance(context).insertBatch(valueList);
        } catch (Throwable t) {
            Log.e(TAG, "importData", t);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Throwable t) {
                Log.e(TAG, "importData close", t);
            }
        }

    }

    /**
     * 申请默认短信应用权限
     */
    public static boolean changeToDefaultSms(Context context) {
        boolean opRet = true;
        String defaultSmsPkg = Telephony.Sms.getDefaultSmsPackage(context);
        String mySmsPkg = context.getPackageName();
        Log.i(TAG, "changeToDefaultSms: " + defaultSmsPkg + mySmsPkg);
        if (!defaultSmsPkg.equals(mySmsPkg)) {
            opRet = false;
            Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, mySmsPkg);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }

        return opRet;
    }
}
